#include<stdio.h>     
#include<stdlib.h>
#include<string.h>

char *my_itoa(int val, char*dst, int rad)
{
	const char arr[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
	int i = 0, cnt = 0;
	unsigned int num = 0;
	char tmp1;
	char *tmp = dst;
	if (val >= 0)
	{
		num = (unsigned)val;
		while (num)               //先用取模方法将各位填到dst数组中
		{
			*tmp = arr[num % rad];
			num /= rad;
			tmp++;
			cnt++;
		}
		for (i = 0; i <= (cnt - 1) / 2; i++)  //再交换回来
		{
			tmp1 = *(dst + i);
			*(dst + i) = *(dst + cnt - i - 1);
			*(dst + cnt - i - 1) = tmp1;
		}
		*tmp = '\0';
		return dst;
	}
	else
	{
		if (rad == 10)   //权值为10时，才区分正负；否则都按无符号数处理
		{
			num = -val;
			*tmp++ = '-';
		}
		else
			num = (unsigned)val;

		while (num)
		{
			*tmp = arr[num % rad];
			num /= rad;
			tmp++;
			cnt++;
		}
		if (rad == 10)
		{
			for (i = 1; i <= (cnt + 1) / 2; i++)
			{
				tmp1 = *(dst + i);
				*(dst + i) = *(dst + cnt - i + 1);
				*(dst + cnt - i + 1) = tmp1;
			}
		}
		else
		{
			for (i = 0; i <= (cnt - 1) / 2; i++)
			{
			tmp1 = *(dst + i);
			*(dst + i) = *(dst + cnt - i - 1);
			*(dst + cnt - i - 1) = tmp1;
			}
		}
		*tmp = '\0';
		return dst;
	}
}

char *my_itoa2(int val, char*dst, int rad)
{
	const char arr[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
	int i = 0, cnt = 0;
	unsigned int num = 0;
	char tmp1;
	char *tmp = dst;

	if (rad == 10)   //权值为10时，才区分正负；否则都按无符号数处理
	{
		num = -val;*tmp++ = '-';cnt++;
	}
	else
		num = (unsigned)val;

	while (num)   //先用取模方法将各位填到dst数组中
	{
		*tmp = arr[num % rad];
		num /= rad;
		tmp++;cnt++;
	}

	if (rad == 10 && val < 0)   //如果权值为10且val<0，特殊处理一下
	{
		i = 1;cnt += 1;
	}		
	for (; i <= (cnt - 1) / 2; i++)  //再交换回来
	{
		tmp1 = *(dst + i);
		*(dst + i) = *(dst + cnt - i - 1);
		*(dst + cnt - i - 1) = tmp1;
	}
	return dst;
}

int main()
{
	int val = -12345;
	char dst[33] = { 0 };
	my_itoa(val, dst, 10);
	printf("%s\n", dst);

	char dst1[33] = { 0 };
	my_itoa2(val, dst1, 10);
	printf("%s\n", dst1);

	return 0;
}
